<?php
/** 环迅主动对账地址 每隔一段时间都会重发请求到这里直到收到'ipscheckok' 防止掉单 处理所有返回请求
 * 目前只有电脑上的支付订单和电脑上的充值
 * Created by PhpStorm.
 * User: KaZeline
 * Date: 15-9-7
 * Time: 上午11:25
 */

use pft\Log\Log;
include '/var/www/html/new/d/class/Log.class.php';
require("/var/www/html/new/conf/le.je");
require_once("/var/www/html/new/d/alipay/ali_order/func.inc.php");//total_fee fenRun write_logs
$le=new go_sql();
$le->connect();
define('LOG_PATH', '/var/www/html/new/d/module/zax/ips_pay/log/log_zddz.txt');
$sourceT = 3;

$ordern = $_GET['billno'];
$amount = $_GET['amount'];
$mydate = $_GET['date'];
$succ = $_GET['succ'];
$msg = $_GET['msg'];
$attach = $_GET['attach'];
$ipsbillno = $_GET['ipsbillno'];
$retEncodeType = $_GET['retencodetype'];
$currency_type = $_GET['Currency_type'];
$signature = $_GET['signature'];

$content = 'billno'.$ordern.'currencytype'.$currency_type.'amount'.$amount.
    'date'.$mydate.'succ'.$succ.'ipsbillno'.$ipsbillno.'retencodetype'.$retEncodeType;
$cert = '6868423594683207055317415846359181319229560680572746757844258714459288782574783'.
    '5274502434575961846130383064183151730364216831296';

$signature_1ocal = md5($content . $cert);

$word = date('Y-m-d H:i:s').'记录开始:|' . json_encode($_GET);
Log::writeLog($word, LOG_PATH);
if ($signature_1ocal == $signature){
    if ($succ == 'Y'){
        if(strpos($ordern,'RECHARGE')===0){//充值
            $ordern = str_replace('RECHARGE','',$ordern);
            $str="select status,total_fee,buyer_email from pft_alipay_rec where out_trade_no='$ordern' AND `sourceT`=$sourceT LIMIT 1";
            $GLOBALS['le']->query($str);
            $pay_log_data = $GLOBALS['le']->fetch_assoc();
            if (!$pay_log_data) {
                $word = '支付log不存在'.$str;
                Log::writeLog($word,LOG_PATH);
                $GLOBALS['le']->close();
                exit('交易失败');
            }
            $status = $GLOBALS['le']->f('status');
            if($status==0){
                //回传的信息里单位是元
                $total_fee = $GLOBALS['le']->f("total_fee") ;//数据库中的单位是元
                if ($amount != $total_fee) {
                    $word ='支付金额不等。返回金额:' . $amount . ',实际金额:'. $total_fee;
                    Log::writeLog($word,LOG_PATH);
                    $GLOBALS['le']->close();
                    exit('交易失败');
                }
                $sid =$GLOBALS['le']->f('buyer_email');
                $s = new SoapClient(null,array(
                    "location" => "http://localhost/open/openService/pft_insideMX.php",
                    "uri" => "www.16u.com?ac_16u=16ucom|pw_16u=c33367701511b4f6020ec61ded352059|auth_16u=true"));
                //管理员帐号不加钱
                //$s->PFT_Member_Fund_Modify(1, 0, $pay_total_fee, 0, 0,null,3, 0,'','环迅充值');
                //客户帐号加钱
                if(($res=$s->PFT_Member_Fund_Modify($sid,$sid,$total_fee*100,0,0,null,3,0,'','环迅充值'))!=100){
                    $word ='客户帐号加钱失败,原因:'.$res;
                    Log::writeLog($word,LOG_PATH);
                    exit;
                }
                $ipsbillno;//环迅唯一交易号
                $str=<<<SQL
UPDATE pft_alipay_rec set status=1,dtime=now(),`trade_no`='$ipsbillno'
WHERE out_trade_no='$ordern' AND `sourceT`=$sourceT limit 1
SQL;
                $GLOBALS['le']->query($str);
                $word ='后台处理完毕';
                Log::writeLog($word,LOG_PATH);
                $GLOBALS['le']->close();
                echo 'ipscheckok';
                exit;
            }else{
                $word ='非正常状态{'.$status.'}';
                Log::writeLog($word,LOG_PATH);
                exit('ipscheckok');
            }
        }
        //支付订单
        $str="select status,total_fee from pft_alipay_rec where out_trade_no='$ordern' AND `sourceT`=$sourceT LIMIT 1";
        $GLOBALS['le']->query($str);
        $ipsRes = $GLOBALS['le']->fetch_assoc();
        $royalty_parameters = $ipsRes['royalty_parameters'];
        $total_fee = $ipsRes['total_fee'];
        if($ipsRes['status']==0) {
            if($amount!=$ipsRes['total_fee']){
                $word = '支付金额不等。返回金额:' . $amount . ',实际金额:'. $total_fee;
                Log::writeLog($word,LOG_PATH);
                $GLOBALS['le']->close();
                exit('交易失败');
            }

            //更新记录状态为已支付
            $str="update pft_alipay_rec set status=1,dtime=now(),trade_no='$ipsbillno' where out_trade_no='$ordern' AND sourceT=$sourceT  limit 1";
            $GLOBALS['le']->query($str);

            $s = new SoapClient(null,array(
                "location" => "http://localhost/open/openService/pft_insideMX.php",
                "uri" => "www.16u.com?ac_16u=16ucom|pw_16u=c33367701511b4f6020ec61ded352059|auth_16u=true"));
            require("/var/www/html/new/d/class/OrderRecord.php");

            $or=new OrderRecord($ordern,$s);

            $orders=$or->info();
            $mainOrder=$orders['mainOrder'];
            $mid=(string)$mainOrder->UUmid;
            $aid=(string)$mainOrder->UUaid;

            if((string)$orders['mainOrder']->UUpaystatus==1) {
                $word = '订单已支付';
                Log::writeLog($word, LOG_PATH);
            }
            $alipay_to_pft = true;
            $total_fee = total_fee($orders,1);// 获取总价格
            $p_type = 6;//环迅支付
            if($aid!=$mid) {
                // 非自身供应须分润  返回值是上级的利润
                $aid_money = fenRun($s, $ordern, $aid, $mid, $total_fee, $orders, $alipay_to_pft,$p_type);
            } else{// 支付给票付通需给自供自销的分销商加上相应金额
                if($alipay_to_pft){
                    $s->PFT_Member_Fund_Modify($mid, 0, $total_fee, 0, 0,null,0, 1,$ordern,$p_type);
                }
            }

            //更新远端订单号,环迅支付
            $s->Remote_Ordernum_Update(serialize(array($ordern=>'PC_IPS_PFT_'.$_SERVER['REQUEST_TIME'])));
            /*只更新订单支付状态*/
            $s->Mod_Order_Status($ordern,1,8);//1表示paystatus改成1 已支付   8表示 pmode改成8 环迅支付

            // 支付后交互
            $tid = (int)$orders['mainOrder']->UUtid;
            $sql = "select Mpath,Mdetails from uu_jq_ticket where id=$tid limit 1";
            $GLOBALS['le']->query($sql);
            $GLOBALS['le']->fetch_assoc();
            if(($Mpath=$GLOBALS['le']->f('Mpath'))){

                $relation_info_req = http_build_query(array(
                    'Action'  => 'Relation_after_pay',
                    'Ordern'  => $ordern,
                    'Fid'     => (int)$orders['mainOrder']->UUmid,
                ));
                file_get_contents($Mpath.'?'.$relation_info_req);
            }
            //最后重发短信
            include '/var/www/html/new/d/class/OrderSmsManual.class.php';
            $smsManual  = new \PFT\SMS\OrderSmsManual($s);
            $ret = $smsManual->SendByOrderInfo($orders,true,false);//通知供应商 不发送微信通知

            $word = date('Y-m-d H:i:s').'交易成功！后台处理完毕|';
            Log::writeLog($word, LOG_PATH);
            echo 'ipscheckok';
            $GLOBALS['le']->close();
            exit;
        }else{
            $word = date('Y-m-d H:i:s').'状态已完成';
            Log::writeLog($word, LOG_PATH);
            $GLOBALS['le']->close();
            echo 'ipscheckok';
            exit;
        }
    }else{
        $word = date('Y-m-d H:i:s').'Succ不为"Y"|';
        Log::writeLog($word, LOG_PATH);
        echo '交易失败！';
        exit;
    }
}else{
    $word = date('Y-m-d H:i:s') . '签名不正确!';
    Log::writeLog($word,LOG_PATH);
    echo '签名不正确！';
    exit;
}


// 转分销分润
/**
 * @param $s    soap实例
 * @param $ordern 订单号
 * @param $aid 供应商id
 * @param $mid 分销商id
 * @param $total_fee 金额
 * @param $orders 订单
 * @param $to_pft
 * @param int $p_type /*金额类型 0帐号资金 1支付宝 2供应商处可用资金 3供应商信用额度设置 4财付通 5银联
 * @return int|string
 */


/*
function fenRun($s, $ordern, $aid, $mid, $total_fee, $orders, $to_pft, $p_type = 1)
{
    $aid = !$aid ? (int)$orders['mainOrder']->UUaid : $aid;
    $mid = !$mid ? (int)$orders['mainOrder']->UUmid : $mid;

    $add = 0;
    $cut = 1;
    // 非自供产品获取结算价
    if($aid!=$mid){
        $pid = (string)$orders['mainOrder']->UUpid;// 产品 id
        $begintime = (string)$orders['mainOrder']->UUbegintime;// 游玩时间价格
        $account = (string)$orders['mainOrder']->UUfromt;// 游玩时间价格
        $ret = $s->Dynamic_Price_And_Storage($account,$pid,$begintime,1,0,0,$aid);
        if($ret==105||$ret==1065){
            $total_money = $total_fee;
        }else{
            $obj = simplexml_load_string($ret);
            $total_money = (string)$obj->Rec->UUsprice * (int)$orders['mainOrder']->UUtnum;
            // write_logs("UUsprice".(string)$obj->Rec->UUsprice,"debug.txt");
        }
        if(count($orders['childOrder']) && $orders['mainOrder']->UUp_type!='F'){
            foreach($orders['childOrder'] as $key=>$child){
                $pid = (string)$child->UUpid;// 产品 id
                $ret = $s->Dynamic_Price_And_Storage($account,$pid,$begintime,1,0,0,$aid);
                if($ret!=105 && $ret!=1065){
                    $obj = simplexml_load_string($ret);
                    $total_money += (string)$obj->Rec->UUsprice * (int)$child->UUtnum;
                }
            }
        }
    }
    if($to_pft){
        //票付通总账号加钱——2015年4月13日11:56:33林农说要添加，宝椿提供的代码
        //$s->PFT_Member_Fund_Modify(1, 0, $total_fee, $add, 0,null,0, $p_type,$ordern);
        // 支付给了票付通，购买者账户加钱
        $s->PFT_Member_Fund_Modify($aid, 0, $total_fee, $add, 0, null, 0, $p_type, $ordern);
    }


    // 产品多级销售分润
//    $str="select aids_money from uu_order_fx_details where orderid='$ordern' limit 1";
//    $GLOBALS['le']->query($str);
//    $lirun = $GLOBALS['le']->fetch_assoc();
    $aids_money = unserialize($orders['mainOrder']->UUaids_money);
    if ($aids_money){
        // 子票没有记录分润，获取子票价格
        $childMenoy = array();
        if(count($orders['childOrder']) && $orders['mainOrder']->UUp_type!='F'){
            foreach($orders['childOrder'] as $key=>$child){
                $aids = explode(',',(string)$child->UUaids);
                krsort($aids);
                $aids_price = explode(',',(string)$child->UUaids_price);
                krsort($aids_price);
                foreach($aids as $k=>$et){
                    if($k==0) break;// 最后一个不用操作了
                    $childMenoy[$et]+= $aids_price[$k-1] * (string)$child->UUtnum;
                }
            }
        }
        // 主订单的 aids
        $main_aids = explode(',',(string)$orders['mainOrder']->UUaids);
//        $aids_money = unserialize($lirun['aids_money']);
        $opID = 0;
        foreach($aids_money as $row){
            $fid=$row[0];
            $action = ($row[2]==0) ? $cut : $add;//0减少,1增加和接口相反
            $Mmoney=$row[3];
            if($action==0){ // 加钱
                $ks = array_search($fid,$main_aids);
                $ks = $ks+1;
                $Mmoney += isset($childMenoy[$main_aids[$ks]]) ? $childMenoy[$main_aids[$ks]]:0;
            }else{
                $Mmoney += isset($childMenoy[$fid]) ? $childMenoy[$fid]:0;
            }

            if($row[1]==0){//信用额度
                $dmode = 1;
                $res = $s->PFT_Member_Fund_Modify($fid,$opID,$Mmoney,$action,$dmode,$row[4],0,2,$ordern);
            }else{//资金
                $dmode = 0;
                $res = $s->PFT_Member_Fund_Modify($fid,$opID,$Mmoney,$action,$dmode,NULL,0,0,$ordern);
            }
        }
    }

    return $total_money;// 返回上级利润

}



function total_fee($orders)
{
//    $total_fee = 0;
//    $aid = (int)$orders['mainOrder']->UUaid;
//    $mid = (int)$orders['mainOrder']->UUmid;

//    $id = $id_type = 'TOB' ? (int)$orders['mainOrder']->UUmid :
//        (int)$orders['mainOrder']->UUaid;
    $id = (int)$orders['mainOrder']->UUmid;
    $total_fee = ((int)$orders['mainOrder']->UUtprice * (int)$orders['mainOrder']->UUtnum);
    $ordernum = (string)$orders['mainOrder']->UUordernum;

    //daction=1 表示退款时 钱会退到账户余额中 而不会原路退回
    $str = <<<SQL
insert pft_member_alipay set fid=$id,orderid='$ordernum',
total_fee='$total_fee',money='$total_fee',ali_account='',rectime=now(),dtype=0,daction=1
SQL;
    $GLOBALS['le']->query($str);

    // 加上非套票的子票价格
    if(count($orders['childOrder']) && $orders['mainOrder']->UUp_type!='F'){
        foreach($orders['childOrder'] as $key=>$child){
            $tmp = ((string)$child->UUtprice * (string)$child->UUtnum);
            $total_fee += $tmp;
            $ordernum = (string)$child->UUordernum;
            $str = <<<SQL
insert pft_member_alipay set fid=$id,orderid='$ordernum',total_fee='$tmp',
money='$tmp',ali_account='',rectime=now(),dtype=0,daction=1
SQL;
            $GLOBALS['le']->query($str);
        }
    }
    return $total_fee;
}
*/

?>








